# coding=utf-8
# 防止中文乱码
import json
import time
import copy

import requests

from common.dbhelper import dbhelper
from common.utils.tool import jdataToString


def apiEvent(apiEvent, values):
  try:
    return eval(apiEvent)(values)
  except Exception as e:
    print("api error: {0}".format(e))
    errorMsg = {
      "result": "-1",
      "module": "userapi",
      "func": apiEvent,
      "values": values,
      "message": "请求数据错误！"
    }
    return json.dumps(errorMsg, ensure_ascii=False)

def addAppPath(values):
  provinceId = values.get('provinceId')
  provinceName = values.get('provinceName')
  tag = values.get('tag')
  IOSPath = values.get('IOSPath')
  IOSNeedPwd = values.get('IOSNeedPwd')
  IOSPassword = values.get('IOSPassword')
  IOSVersion = values.get('IOSVersion')
  IOSUpdateTime = values.get('IOSUpdateTime')
  IOSIconUrl = values.get('IOSIconUrl')
  IOSName = values.get('IOSName')
  IOSShort = values.get('IOSShort')
  AndroidPath = values.get('AndroidPath')
  AndroidNeedPwd = values.get('AndroidNeedPwd')
  AndroidPassword = values.get('AndroidPassword')
  AndroidVersion = values.get('AndroidVersion')
  AndroidUpdateTime = values.get('AndroidUpdateTime')
  AndroidIconUrl = values.get('AndroidIconUrl')
  AndroidName = values.get('AndroidName')
  AndroidShort = values.get('AndroidShort')

  name = provinceName + '-' + tag

  sql0 = "SELECT * FROM appspath WHERE Name = '"+name+"'"
  arr = dbhelper.DBHelper().selectHelper(sql0)
  if arr:
    edata = {
      "result": "-1",
      "message": "已存在您维护的下载地址，如果要修改请编辑对应数据"
    }
    return json.dumps(edata, ensure_ascii=False)

  nowt = str(int(time.time() * 1000))

  sql = "INSERT INTO appspath (ProvinceId, ProvinceName, Tag, Name, CreatedTime, ModifyTime, State, IOSPath, IOSPassword, IOSVersion, IOSUpdateTime, IOSIconUrl, IOSName, IOSShort, IOSNeedPwd, AndroidPath, AndroidPassword, AndroidVersion, AndroidUpdateTime, AndroidIconUrl, AndroidName, AndroidShort, AndroidNeedPwd) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (provinceId, provinceName, tag, name, nowt, nowt, '1', IOSPath, IOSPassword, IOSVersion, IOSUpdateTime, IOSIconUrl, IOSName, IOSShort, IOSNeedPwd, AndroidPath, AndroidPassword, AndroidVersion, AndroidUpdateTime, AndroidIconUrl, AndroidName, AndroidShort, AndroidNeedPwd)

  dbhelper.DBHelper().transactionHelper(sql)

  jdata = {
    "result": "1",
    "message": '保存成功！'
  }
  return jdataToString(jdata)

def editAppPath(values):
  id = values.get('id')
  IOSPath = values.get('IOSPath')
  IOSNeedPwd = values.get('IOSNeedPwd')
  IOSPassword = values.get('IOSPassword')
  IOSVersion = values.get('IOSVersion')
  IOSUpdateTime = values.get('IOSUpdateTime')
  IOSIconUrl = values.get('IOSIconUrl')
  IOSName = values.get('IOSName')
  IOSShort = values.get('IOSShort')
  AndroidPath = values.get('AndroidPath')
  AndroidNeedPwd = values.get('AndroidNeedPwd')
  AndroidPassword = values.get('AndroidPassword')
  AndroidVersion = values.get('AndroidVersion')
  AndroidUpdateTime = values.get('AndroidUpdateTime')
  AndroidIconUrl = values.get('AndroidIconUrl')
  AndroidName = values.get('AndroidName')
  AndroidShort = values.get('AndroidShort')

  sql0 = "SELECT * FROM appspath WHERE ID = '"+id+"'"
  arr = dbhelper.DBHelper().selectHelper(sql0)
  if not arr:
    edata = {
      "result": "-1",
      "message": "编辑出错，编辑数据项不存在！"
    }
    return json.dumps(edata, ensure_ascii=False)

  nowt = str(int(time.time() * 1000))

  sql = "UPDATE appspath SET IOSPath = '%s', IOSPassword = '%s', IOSVersion = '%s', IOSUpdateTime = '%s', IOSIconUrl = '%s', IOSName = '%s', IOSShort = '%s', IOSNeedPwd = '%s', AndroidPath = '%s', AndroidPassword = '%s', AndroidVersion = '%s', AndroidUpdateTime = '%s', AndroidIconUrl = '%s', AndroidName = '%s', AndroidShort = '%s', AndroidNeedPwd = '%s', ModifyTime = '%s' WHERE ID = '%s'" % (IOSPath, IOSPassword, IOSVersion, IOSUpdateTime, IOSIconUrl, IOSName, IOSShort, IOSNeedPwd, AndroidPath, AndroidPassword, AndroidVersion, AndroidUpdateTime, AndroidIconUrl, AndroidName, AndroidShort, AndroidNeedPwd, nowt, id)

  dbhelper.DBHelper().transactionHelper(sql)

  jdata = {
    "result": "1",
    "message": '数据更新成功！'
  }
  return jdataToString(jdata)

def enable(values):
  id = values.get('id')

  sql0 = "SELECT * FROM appspath WHERE ID = '" + id + "'"
  arr = dbhelper.DBHelper().selectHelper(sql0)
  if not arr:
    edata = {
      "result": "-1",
      "message": "编辑出错，编辑数据项不存在！"
    }
    return json.dumps(edata, ensure_ascii=False)

  nowt = str(int(time.time() * 1000))

  sql = "UPDATE appspath SET State = '%s', ModifyTime = '%s' WHERE ID = '%s'" % ('1', nowt, id)

  dbhelper.DBHelper().transactionHelper(sql)

  jdata = {
    "result": "1",
    "message": '启用成功！'
  }
  return jdataToString(jdata)

def disable(values):
  id = values.get('id')

  sql0 = "SELECT * FROM appspath WHERE ID = '" + id + "'"
  arr = dbhelper.DBHelper().selectHelper(sql0)
  if not arr:
    edata = {
      "result": "-1",
      "message": "编辑出错，编辑数据项不存在！"
    }
    return json.dumps(edata, ensure_ascii=False)

  nowt = str(int(time.time() * 1000))

  sql = "UPDATE appspath SET State = '%s', ModifyTime = '%s' WHERE ID = '%s'" % ('2', nowt, id)

  dbhelper.DBHelper().transactionHelper(sql)

  jdata = {
    "result": "1",
    "message": '禁用成功！'
  }
  return jdataToString(jdata)

def delete(values):
  id = values.get('id')

  sql = "DELETE FROM appspath WHERE ID = '%s'" % (id)
  dbhelper.DBHelper().transactionHelper(sql)

  jdata = {
    "result": "1",
    "message": '删除成功！'
  }
  return jdataToString(jdata)

def getAppPaths(values):
  searchKey = values.get('searchKey')
  if not searchKey:
    searchKey = ''

  sql = "SELECT * FROM appspath WHERE Name like '%" + searchKey + "%' "

  state = values.get('state')
  if state and state != '10':
    sql += "AND State = '" + state + "' "
  sql += 'ORDER BY ProvinceId'

  arr = dbhelper.DBHelper().selectHelper(sql)
  data = []

  for row in arr:
    rowj = {
      'id': str(row['ID']),
      'name': str(row['Name']),
      'times': str(row['Times']),
      'state': str(row['State']),
      'createdTime': str(row['CreatedTime']),
      'modifyTime': str(row['ModifyTime']),
      'provinceId': str(row['ProvinceId']),
      'provinceName': str(row['ProvinceName']),
      'tag': str(row['Tag']),
      'IOSPath': str(row['IOSPath']),
      'IOSNeedPwd': str(row['IOSNeedPwd']),
      'IOSPassword': str(row['IOSPassword']),
      'IOSVersion': str(row['IOSVersion']),
      'IOSUpdateTime': str(row['IOSUpdateTime']),
      'IOSIconUrl': str(row['IOSIconUrl']),
      'IOSName': str(row['IOSName']),
      'IOSShort': str(row['IOSShort']),
      'AndroidPath': str(row['AndroidPath']),
      'AndroidNeedPwd': str(row['AndroidNeedPwd']),
      'AndroidPassword': str(row['AndroidPassword']),
      'AndroidVersion': str(row['AndroidVersion']),
      'AndroidUpdateTime': str(row['AndroidUpdateTime']),
      'AndroidIconUrl': str(row['AndroidIconUrl']),
      'AndroidName': str(row['AndroidName']),
      'AndroidShort': str(row['AndroidShort'])
    }
    data.append(rowj)

  jdata = {
    "result": "1",
    "data": data
  }
  return jdataToString(jdata)


def setDataInfo(orgin, appInfo):
  if appInfo['type'] == 'ios':
    orgin['IOSPath'] = 'https://www.betaqr.com/' + appInfo['short']
    orgin['IOSVersion'] = appInfo['releases']['master']['version'] + '（build：' + appInfo['releases']['master']['build'] + '）'
    orgin['IOSUpdateTime'] = int(appInfo['releases']['master']['created_at']) * 1000
    orgin['IOSName'] = appInfo['name']
    orgin['IOSShort'] = appInfo['short']
    orgin['IOSIconUrl'] = appInfo['icon_url']
  elif appInfo['type'] == 'android':
    orgin['AndroidPath'] = 'https://www.betaqr.com/' + appInfo['short']
    orgin['AndroidVersion'] = appInfo['releases']['master']['version'] + '（build：' + appInfo['releases']['master'][
      'build'] + '）'
    orgin['AndroidUpdateTime'] = int(appInfo['releases']['master']['created_at']) * 1000
    orgin['AndroidName'] = appInfo['name']
    orgin['AndroidShort'] = appInfo['short']
    orgin['AndroidIconUrl'] = appInfo['icon_url']

  return orgin;


def task_UpdataInfos(values={}):
  list = []
  d = {}
  try:
    lisData = json.loads(getAppPaths(values))['data']

    for data in lisData:
      newData = copy.deepcopy(data)

      d = {}
      d['name'] = newData['name']

      # if newData['name'] == '贵州省-正式包':
      #   print(newData)

      IOSShort = data['IOSShort']
      if IOSShort and IOSShort != '':
        url = "https://fir-download.fircli.cn/" + IOSShort
        iosPwd = data['IOSPassword']
        headers = {}
        if iosPwd and iosPwd != '':
          headers = {'Passwd': iosPwd}
        res = requests.get(url, headers=headers)
        resJson = json.loads(bytes.decode(res.content))
        print(resJson)
        if resJson.get('auth') == True:
          newData = setDataInfo(newData, resJson['app'])
        elif resJson.get('require_pwd') == True:
          newData['IOSNeedPwd'] = '1'
          newData['IOSPassword'] = ''

      AndroidShort = data['AndroidShort']
      if AndroidShort and AndroidShort != '':
        url = "https://fir-download.fircli.cn/" + AndroidShort
        androidPwd = data['AndroidPassword']
        headers = {}
        if androidPwd and androidPwd != '':
          headers = {'Passwd': androidPwd}
        res = requests.get(url, headers=headers)
        resJson = json.loads(bytes.decode(res.content))
        print(resJson)
        if resJson.get('auth') == True:
          newData = setDataInfo(newData, resJson['app'])
        elif resJson.get('require_pwd') == True:
          newData['AndroidNeedPwd'] = '1'
          newData['AndroidPassword'] = ''

      if newData['IOSUpdateTime'] != data['IOSUpdateTime'] or newData['IOSShort'] != data['IOSShort'] or newData['AndroidShort'] != data['AndroidShort'] or newData['AndroidUpdateTime'] != data['AndroidUpdateTime'] or newData['AndroidPassword'] != data['AndroidPassword'] or newData['IOSPassword'] != data['IOSPassword']:
        editAppPath(newData)
      else:
        print(newData['name'] + ' 没有任何更新！')

      d['result'] = True
      list.append(d)

      # time.sleep(1)

    str = ''
    i = 0
    for res in list:
      i = i + 1
      if res['result']:
        str += "<p>%i、name: %s, result: %s</p>" % (i, res['name'], res['result'])
      else:
        str += "<p>%i、name: %s, result: %s, error: %s</p>" % (i, res['name'], res['result'], res['err'])
    str += "<p>全部完成！</p>"
    return str

  except Exception as e:
    print("api error: {0}".format(e))
    print("task_UpdataInfos error！")
    d['err'] = format(e)
    d['result'] = False
    list.append(d)
    str = ''
    i = 0
    for res in list:
      i = i+1
      if res['result']:
        str += "<p>%i、 name: %s, result: %s</p>" % (i, res['name'], res['result'])
      else:
        str += "<p>%i、 name: %s, result: %s, error: %s</p>" % (i, res['name'], res['result'], res['err'])
    return str
